import { defineConfig, loadEnv } from "vite";
import uni from "@dcloudio/vite-plugin-uni";
import autoprefixer from "autoprefixer";
import AutoImport from "unplugin-auto-import/vite";
import ViteRestart from "vite-plugin-restart";
import uniPages from "@uni-helper/vite-plugin-uni-pages";
import uniLayout from "@uni-helper/vite-plugin-uni-layouts";
import Components from "unplugin-vue-components/vite";
import viteCompression from "vite-plugin-compression";
import dayjs from "dayjs";
import { visualizer } from "rollup-plugin-visualizer";
import path from "node:path";

import IconsResolver from "unplugin-icons/resolver";
import Icons from "unplugin-icons/vite";
import fs from "fs";
import type { Loader } from "esbuild";

function removeJSComments(code) {
  const singleLineCommentRegex = /\/\/.*(?=\n)/g;
  const multiLineCommentRegex = /\/\*[\s\S]*?\*\//g;

  code = code.replace(multiLineCommentRegex, "");
  code = code.replace(singleLineCommentRegex, "");

  return code;
}
const htmlPlugin = () => {
  return {
    name: "html-transform",
    transformIndexHtml(html: string) {
      return html.replace("%BUILD_DATE", dayjs().format("YYYY-MM-DD HH:mm:ss"));
    },
  };
};

// https://vitejs.dev/config/
export default async ({ mode }) => {
  // mode:区分是生产 环境还是 开发环境
  // process.env.cwd(): 项目根目录
  // loadEnv(mode, process.env.cwd()): 加载环境变量文件
  const env = loadEnv(mode, path.resolve(process.cwd(), "env"));
  const isProduction = mode === "production";
  console.log("env", env);
  const UnoCSS = await import("unocss/vite").then((i) => i.default);
  return defineConfig({
    plugins: [
      uniPages(),
      uniLayout(),
      uni(),
      UnoCSS(),
      Icons(),
      htmlPlugin(),
      Components({
        dirs: ["src/components"], // 目标文件夹
        extensions: ["vue"], // 文件类型
        dts: "src/types/components.d.ts", // 输出文件，里面都是一些import的组件键值对
        // ui库解析器，也可以自定义，需要安装相关UI库
        resolvers: [IconsResolver()],
      }),
      AutoImport({
        imports: ["vue", "uni-app", "pinia"],
        dts: "src/types/auto-imports.d.ts",
      }),
      ViteRestart({
        restart: ["vite.config.ts"],
      }),
      // 打包分析
      isProduction && visualizer(),
      isProduction && viteCompression(),
    ],
    optimizeDeps: {
      esbuildOptions: {
        plugins: [
          {
            name: "pako:dep-scan",
            setup(build) {
              build.onLoad(
                { filter: /\.(?:j|t)sx?$|\.mjs$/ },
                ({ path: id }) => {
                  console.log("id :>> ", id);
                  let ext = path.extname(id).slice(1);
                  if (ext === "mjs") ext = "js";
                  if (
                    fs.existsSync(id) &&
                    id.indexOf("node_modules/pako") > -1
                  ) {
                    let contents = fs.readFileSync(id, "utf-8");
                    if (contents.includes("#endif")) {
                      contents = removeJSComments(contents);
                    }
                    return {
                      loader: ext as Loader,
                      contents,
                    };
                  }
                },
              );
            },
          },
        ],
      },
    },
    resolve: {
      alias: {
        "@": "/src",
      },
    },
    css: {
      postcss: {
        plugins: [
          autoprefixer({
            // 指定目标浏览器
            overrideBrowserslist: ["> 1%", "last 2 versions"],
          }),
        ],
      },
    },
    build: {
      minify: "terser",
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },
    },
    server: {
      host: "0.0.0.0",
      port: 8080,
      open: true,

      proxy: {
        // "^/api": {
        //   target: "https://qbtr.cc",
        //   changeOrigin: true,
        //   rewrite: (path) => path.replace(/^\/api/, ""),
        // },
        "^/back": {
          target: "http://101.35.249.138/back",
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/qd/, ""),
        },
      },
    },
  });
};
